import { useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import Taro from '@tarojs/taro';
import utils from '@/utils/index';

const GetLocation = ({ dispatch, handleLocation = null }) => {
  const locationByIP = useRef({});
  const gpsRef = useRef(false);

  const getLocationByIP = () => {
    let curTimeStamp = new Date().getTime();
    if (
      locationByIP.current.timeStamp &&
      curTimeStamp - locationByIP.current.timeStamp < 5 * 60 * 1000
    ) {
      getLocationByGPS();
    } else {
      dispatch({ type: 'otherApi/getLocationByIPModel' }).then((res) => {
        locationByIP.current = { ...res };
        getLocationByGPS();
      });
    }
  };

  const getLocationByGPS = () => {
    return;
    Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      timeout: 3000,
      success: (res) => {
        const { latitude, longitude } = res;
        const timeStamp = new Date().getTime();
        gpsRef.current = true;
        handleLocation && handleLocation({ latitude, longitude });
        utils.setLocalStorage('location', { latitude, longitude, timeStamp });
      },
      fail: () => {
        if (locationByIP.current.timeStamp) {
          handleLocation && handleLocation({ ...locationByIP.current, noAuth: true });
        } else {
          handleLocation &&
            handleLocation({ latitude: undefined, longitude: undefined, noAuth: true });
        }
      },
    });
  };

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      handleLocation && handleLocation({ latitude, longitude });
    } else {
      getLocationByIP();
    }
  };

  useEffect(() => {
    getLocation();
  }, []);

  return null;
};

export default connect(({}) => ({}))(GetLocation);
